﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using AuditWeb.Models;
using System.Web.Profile;
using AuditModel;

namespace AuditWeb.Controllers
{
    public class AccountController : Controller
    {
        private AuditDBEntities db = new AuditDBEntities();
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    ProfileBase profile = ProfileBase.Create(model.UserName);
                    if ((bool)profile["ChangePassword"])
                    {
                        return RedirectToAction("ChangePassword", "Account");
                    }
                    if (User.IsInRole("评委"))
                    {
                        ExpertJudge ej = db.ExpertJudges.SingleOrDefault(e => e.SerialNumber == model.UserName);
                        if (string.IsNullOrEmpty(ej.ContactAddress) && string.IsNullOrEmpty(ej.ZipCode))
                        {
                            return RedirectToAction("SetContactInfo", "PW");
                        }
                    }
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", AuditResources.UI.LogOnError);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register
        [Authorize(Roles="管理员")]
        public ActionResult Register()
        {
            ViewBag.Roles = GetAllRolesExceptPW();
            ViewBag.SubjectID = new SelectList(db.Subjects, "Id", "Name", AppSettingsHelper.DefaultSubjectID);
            ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name");
            ViewBag.RolesError = "";
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [Authorize(Roles = "管理员")]
        public ActionResult Register(RegisterModel model)
        {
            ViewBag.RolesError = "";
            model.Profile.Roles = new List<string>();
            foreach (string r in GetAllRolesExceptPW())
            {
                if (Request.Form[r].Contains("true"))
                {
                    model.Profile.Roles.Add(r);
                }
            }
            if (model.Profile.Roles != null && model.Profile.Roles.Count > 0)
            {
                if (ModelState.IsValid)
                {
                    // Attempt to register the user
                    MembershipCreateStatus createStatus;
                    Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        //FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                        ProfileBase profile = ProfileBase.Create(model.UserName);
                        profile["CountyCode"] = model.Profile.CountyCode;
                        profile["SubjectId"] = model.Profile.SubjectId;
                        profile["RealName"] = model.Profile.RealName;
                        profile["Telephone"] = model.Profile.Telephone;
                        profile.Save();
                        Roles.AddUserToRoles(model.UserName, model.Profile.Roles.ToArray());
                        return RedirectToAction("UserList", "Account");
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(createStatus));
                    }                    
                }
            }
            else
            {
                ViewBag.RolesError = "至少设置一个角色";
            }

            // If we got this far, something failed, redisplay form
            ViewBag.Roles = GetAllRolesExceptPW();
            ViewBag.SubjectID = new SelectList(db.Subjects, "Id", "Name");
            ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name");
            return View(model);
        }

        [Authorize(Roles = "管理员")]
        public ActionResult UserList(string rolename)
        {
            MembershipUserCollection users=  Membership.GetAllUsers();
            IList<ProfileModel> userlist = new List<ProfileModel>();
            foreach (MembershipUser user in users)
            {
                if(!Roles.IsUserInRole(user.UserName,"评委")&&!Roles.IsUserInRole(user.UserName,"准评委"))
                {
                    if (!string.IsNullOrEmpty(rolename))
                    {
                        if (Roles.IsUserInRole(user.UserName, rolename))
                        {
                            ProfileModel model = CreateProfileModel(user.UserName);
                            userlist.Add(model);
                        }
                    }
                    else
                    {
                        ProfileModel model = CreateProfileModel(user.UserName);
                        userlist.Add(model);
                    }
                }
            }
            ViewBag.rolename = new SelectList((from r in Roles.GetAllRoles() where r != "评委" && r != "准评委" select r).ToList(), rolename);
            return View(userlist);
        }

        ProfileModel CreateProfileModel(string username)
        {
            ProfileBase profile = ProfileBase.Create(username);
            ProfileModel model = new ProfileModel()
            {
                Username = username,
                CountyCode = profile["CountyCode"]!=null?profile["CountyCode"].ToString():"", 
                RealName = profile["RealName"]!=null?profile["RealName"].ToString():"",
                SubjectId = (int)profile["SubjectId"],
                Telephone = profile["Telephone"]!=null?profile["Telephone"].ToString():"",
                Roles = Roles.GetRolesForUser(username)
            };
            return model;
        }

        [Authorize(Roles = "管理员")]
        public ActionResult EditProfile(string username)
        {
            ProfileModel model = CreateProfileModel(username);
            ViewBag.Roles = GetAllRolesExceptPW();
            ViewBag.SubjectID = new SelectList(db.Subjects, "Id", "Name",model.SubjectId);
            ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name", model.CountyCode);
            ViewBag.RolesError = "";
            return View(model);
        }

        [Authorize(Roles = "管理员")]
        [HttpPost]
        public ActionResult EditProfile(ProfileModel model)
        {
            //IEnumerable<string> oldroles=model.Roles;
            //model.Roles.Clear();
            ViewBag.RolesError = "";
            model.Roles = new List<string>();
            foreach (string r in GetAllRolesExceptPW())
            {
                if (Request.Form[r].Contains("true"))
                {
                    model.Roles.Add(r);
                }
            }
            if (model.Roles != null && model.Roles.Count > 0)
            {
                if (ModelState.IsValid)
                {
                    ProfileBase profile = ProfileBase.Create(model.Username);
                    profile["CountyCode"] = model.CountyCode;
                    profile["SubjectId"] = model.SubjectId;
                    profile["RealName"] = model.RealName;
                    profile["Telephone"] = model.Telephone;
                    profile.Save();
                    string[] roleNames = Roles.GetRolesForUser(model.Username);
                    if (roleNames.Length>0)
                    {
                        Roles.RemoveUserFromRoles(model.Username, roleNames);
                    }
                    Roles.AddUserToRoles(model.Username, model.Roles.ToArray());
                    return RedirectToAction("UserList");
                }
            }
            else
            {
                ViewBag.RolesError = "至少设置一个角色";
            }
            ViewBag.Roles = GetAllRolesExceptPW();
            ViewBag.SubjectID = new SelectList(db.Subjects, "Id", "Name", model.SubjectId);
            ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name", model.CountyCode);
            
            return View(model);
        }

        string[] GetAllRolesExceptPW()
        {
            var roles = from role in Roles.GetAllRoles()
                        where !role.Contains("评委") 
                        select role;
            return roles.ToArray();
        }
        
        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (model.OldPassword == model.NewPassword)
            {
                ModelState.AddModelError("NewPassword", AuditResources.Account.NewPwdSameAsOldPwd);
            }
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    ProfileBase profile = ProfileBase.Create(User.Identity.Name);
                    profile["ChangePassword"] = false;
                    profile.Save();
                    if (User.IsInRole("准评委") && !User.IsInRole("评委"))
                    {
                        Roles.RemoveUserFromRole(User.Identity.Name, "准评委");
                        Roles.AddUserToRole(User.Identity.Name,"评委");
                        return RedirectToAction("SetContactInfo", "PW");
                    }
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "密码不正确.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            
            return View();
        }

        //
        // GET: /AnnualEvent/Delete/5
        [Authorize(Roles = "管理员")]
        public ActionResult Delete(string username)
        {
            ProfileModel model = CreateProfileModel(username);
            ViewBag.Roles = GetAllRolesExceptPW();
            ViewBag.SubjectID = new SelectList(db.Subjects, "Id", "Name", model.SubjectId);
            ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name", model.CountyCode);
            ViewBag.RolesError = "";
            return View(model);
        }

        //
        // POST: /AnnualEvent/Delete/5
        [Authorize(Roles = "管理员")]
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string username)
        {
            Membership.DeleteUser(username);
            return RedirectToAction("UserList");
        }

        //Reset Password
        [Authorize(Roles = "管理员")]
        public ActionResult ResetPassword(string username)
        {
            MembershipUser user = Membership.GetUser(username);
            ViewBag.NewPassword=user.ResetPassword();
            return View();
        }

        



        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }

}
